import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Table } from 'semantic-ui-react'
import { Query, Subscription } from 'react-apollo'
import { listTable as listTableDuck } from 'ducks'
import produce from 'immer'
import Holder from './holder'
import Loading from './loading'
import Modal from './confirmModal'

class ListData extends Component {
  componentWillUnmount = () => {
    const { actionReset } = this.props
    actionReset()
  }

  getSortObject = (sort) => {
    const strs = sort.split('-')
    return { [strs[0]]: strs[1] }
  }

  render() {
    const {
      children,
      query,
      pageInfo,
      queryName,
      actionReciveData,
      actionNumPage,
      variables,
      sortInfo,
      searchInfo,
      holder,
      header,
      search,
      sort,
      subscription,
    } = this.props

    if (!pageInfo.activeNum) {
      return null
    }

    const variablesFinal = produce(variables, (draftState) => {
      if (sort) draftState.order.push(this.getSortObject(sortInfo))
      draftState.offset = (pageInfo.activeNum - 1) * pageInfo.limit
      if (search) draftState.search = searchInfo ? `%${searchInfo}%` : '%%'
    })

    if (subscription) {
      return (
        <Subscription subscription={query} variables={variablesFinal} fetchPolicy="network-only">
          {({
            loading, error, data, refetch,
          }) => {
            if (loading) return <Loading />
            if (error) return `Error! ${error.message}`
            const childrenWithProps = React.Children.map(children, child => React.cloneElement(child, { data }))
            if (pageInfo.number === 0 && holder) {
              return <Holder holder={holder} />
            }
            return (
              <React.Fragment>
                <Table basic="very" style={{ marginBottom: '2em' }}>
                  {header}
                  <Table.Body>{childrenWithProps}</Table.Body>
                </Table>
                <Modal reFetch={refetch} />
              </React.Fragment>
            )
          }}
        </Subscription>
      )
    }
    return (
      <Query query={query} variables={variablesFinal} fetchPolicy="network-only">
        {({
          loading, error, data, refetch,
        }) => {
          if (loading) return <Loading />
          if (error) return `Error! ${error.message}`
          const childrenWithProps = React.Children.map(children, child => React.cloneElement(child, { data }))
          if (pageInfo.number === 0 && holder) {
            return <Holder holder={holder} />
          }
          return (
            <React.Fragment>
              <Table basic="very" style={{ marginBottom: '2em' }}>
                {header}
                <Table.Body>{childrenWithProps}</Table.Body>
              </Table>
              <Modal reFetch={refetch} />
            </React.Fragment>
          )
        }}
      </Query>
    )
  }
}

const mapStateToProps = state => ({
  pageInfo: listTableDuck.selectors.pageInfo(state),
  sortInfo: listTableDuck.selectors.sortInfo(state),
  searchInfo: listTableDuck.selectors.searchInfo(state),
})

const mapDispatchToProps = {
  actionReset: listTableDuck.creators.actionReset,
}

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(ListData)
